'use strict'

const Controller = require('egg').Controller
const axios = require('axios')
// 配置信息
const clientID = 'be9c1e97a29d4f372d81'
const clientSecret = '11751cdb9c2b75f34f9e52dd12f0b94306ab6edc'

class AuthTwo extends Controller {
	async auth() {
		// 1. 接受 code
		const code = this.ctx.query.code
		// 2. 带上code请求授权接口
		const result = await axios.post(
			`https://github.com/login/oauth/access_token?client_id=${clientID}&client_secret=${clientSecret}&${code}`
		)
		console.log(result, 'result')
		// 3. 从授权接口拿到token ,然后，请求第三方应用的用户信息接口
		const access_token = result.data.access_token

		const userInfo = await axios.get(`https://api.github.com/user`, {
			headers: {
				accept: 'application/json',
				Authorization: `token ${access_token}`
			}
		})
		console.log(userInfo, 'userInfo')
		// 用户名字（github中的账号名字）
		const name = userInfo.data.login
		// 头像
		const avatar = userInfo.data.avatar_url
		// 4. 重定向回到前端页面
		this.ctx.response.redirect(
			`http://localhost:8080/#/home?avatar=${avatar}&name=${name}`
		)
	}
}
module.exports = AuthTwo
